package hdelsot

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"pipe-guard/cache"
	"pipe-guard/models"
	"strconv"
	"time"
)

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))

	size, _ := strconv.Atoi(c.DefaultQuery("size", "3"))

	offstr := (page - 1) * size

	var count int64
	models.DB.Model(&models.Are{}).Count(&count)

	var ares []models.Are

	redis_key := "redis_list"
	po, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if po == "" {
		models.DB.Offset(offstr).Limit(size).Find(&ares)
		jsonlist, _ := json.Marshal(ares)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonlist, time.Hour*2)
	} else {
		json.Unmarshal([]byte(po), &ares)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": gin.H{
			"count": count,
			"ares":  ares,
		},
	})
	return
}
func Xq(c *gin.Context) {
	id := c.Query("id")
	var ares models.Are

	redis_key := "redis_list" + id
	po, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if po == "" {
		models.DB.Where("id=?", id).First(&ares)
		jsonlist, _ := json.Marshal(ares)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonlist, time.Hour*2)
	} else {
		json.Unmarshal([]byte(po), &ares)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": ares,
	})
	return
}
